<!-- 时间轴组件 -->
<template>
  <div class="timeline-container">
    <div class="timeline-header">
      <div class="header-actions">
        <n-button-group size="small">
          <n-button quaternary @click="addKeyframe" :disabled="!selectedTrack">
            <template #icon><n-icon><AddOutline /></n-icon></template>
            添加关键帧
          </n-button>
          <n-button quaternary @click="removeKeyframe" :disabled="!selectedKeyframe">
            <template #icon><n-icon><TrashOutline /></n-icon></template>
            删除关键帧
          </n-button>
        </n-button-group>
      </div>
      
      <div class="header-center">
        <n-space>
          <n-button-group size="small">
            <n-button quaternary @click="goToPrevKeyframe">
              <template #icon><n-icon><PlaySkipBackOutline /></n-icon></template>
            </n-button>
            <n-button quaternary @click="goToNextKeyframe">
              <template #icon><n-icon><PlaySkipForwardOutline /></n-icon></template>
            </n-button>
          </n-button-group>
          
          <n-input-number 
            v-model:value="currentTime" 
            :min="0" 
            :max="totalDuration"
            :step="0.1"
            size="small"
            style="width: 80px"
          />
        </n-space>
      </div>
      
      <div class="header-right">
        <n-select 
          v-model:value="zoom" 
          :options="zoomOptions" 
          size="small"
          style="width: 100px"
        />
      </div>
    </div>
    
    <div class="timeline-body">
      <div class="timeline-sidebar">
        <div class="track-header">
          <span>轨道</span>
          <n-button quaternary circle size="tiny" @click="addTrack">
            <template #icon><n-icon><AddOutline /></n-icon></template>
          </n-button>
        </div>
        
        <div class="track-list">
          <timeline-track
            v-for="track in tracks"
            :key="track.id"
            :track="track"
            :is-selected="selectedTrack?.id === track.id"
            @select="selectTrack"
            @update:track="updateTrack"
          />
        </div>
      </div>
      
      <div class="timeline-content" ref="timelineContent">
        <timeline-ruler 
          :total-duration="totalDuration"
          :zoom="zoom"
          @seek="seekToTime"
        />
        
        <div class="timeline-tracks-container">
          <div 
            v-for="track in tracks" 
            :key="track.id"
            class="track-content"
            :class="{ 'selected': selectedTrack?.id === track.id }"
          >
            <keyframe-item
              v-for="keyframe in track.keyframes"
              :key="keyframe.id"
              :keyframe="keyframe"
              :position="keyframe.time * zoom"
              :is-selected="selectedKeyframe?.id === keyframe.id"
              @select="selectKeyframe"
              @drag-start="startKeyframeDrag"
            />
          </div>
          
          <time-indicator
            :position="currentTime * zoom"
            @drag-start="startTimeIndicatorDrag"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted, onBeforeUnmount } from 'vue'
import { 
  NButton, 
  NButtonGroup, 
  NIcon, 
  NSpace, 
  NInputNumber, 
  NSelect 
} from 'naive-ui'
import { 
  AddOutline, 
  TrashOutline, 
  PlaySkipBackOutline, 
  PlaySkipForwardOutline 
} from '@vicons/ionicons5'
import TimelineTrack from './TimelineTrack.vue'
import TimelineRuler from './TimelineRuler.vue'
import KeyframeItem from './KeyframeItem.vue'
import TimeIndicator from './TimeIndicator.vue'
import { throttle } from '../../utils/tools'
import { Track, Keyframe, DragState, ZOOM_OPTIONS } from '../../types/editor'

// 定义属性
const props = defineProps({
  tracks: {
    type: Array as () => Track[],
    required: true
  },
  currentTime: {
    type: Number,
    required: true
  },
  totalDuration: {
    type: Number,
    required: true
  },
  selectedTrack: {
    type: Object as () => Track | null,
    default: null
  },
  selectedKeyframe: {
    type: Object as () => Keyframe | null,
    default: null
  }
})

// 定义事件
const emit = defineEmits([
  'update:current-time',
  'select-track',
  'select-keyframe',
  'add-track',
  'add-keyframe',
  'remove-keyframe',
  'update-track',
  'update-keyframe'
])

// 时间线缩放选项
const zoom = ref(10)
const zoomOptions = [
  { label: '25%', value: 2.5 },
  { label: '50%', value: 5 },
  { label: '100%', value: 10 },
  { label: '200%', value: 20 },
  { label: '400%', value: 40 }
]

// 时间线内容容器引用
const timelineContent = ref<HTMLElement | null>(null)

// 拖动状态
const dragState = ref<DragState>({
  isDragging: false,
  type: '',
  startX: 0,
  startY: 0,
  targetId: '',
  originalValue: null
})

// 选择轨道
const selectTrack = (track: Track) => {
  emit('select-track', track)
}

// 选择关键帧
const selectKeyframe = (keyframe: Keyframe) => {
  emit('select-keyframe', keyframe)
}

// 添加轨道
const addTrack = () => {
  emit('add-track')
}

// 添加关键帧
const addKeyframe = () => {
  if (!props.selectedTrack) return
  
  const newKeyframe: Keyframe = {
    id: `keyframe-${Date.now()}`,
    time: props.currentTime,
    value: {}
  }
  
  emit('add-keyframe', props.selectedTrack, newKeyframe)
}

// 删除关键帧
const removeKeyframe = () => {
  if (!props.selectedTrack || !props.selectedKeyframe) return
  emit('remove-keyframe', props.selectedTrack, props.selectedKeyframe)
}

// 更新轨道
const updateTrack = (track: Track) => {
  emit('update-track', track)
}

// 跳转到指定时间
const seekToTime = (time: number) => {
  emit('update:current-time', Math.max(0, Math.min(props.totalDuration, time)))
}

// 跳转到上一个关键帧
const goToPrevKeyframe = () => {
  if (!props.selectedTrack) return
  
  const keyframes = [...props.selectedTrack.keyframes].sort((a, b) => a.time - b.time)
  const prevKeyframe = keyframes.findLast(k => k.time < props.currentTime)
  
  if (prevKeyframe) {
    seekToTime(prevKeyframe.time)
  } else if (keyframes.length > 0) {
    // 如果没有上一个，跳到最后一个
    seekToTime(keyframes[keyframes.length - 1].time)
  }
}

// 跳转到下一个关键帧
const goToNextKeyframe = () => {
  if (!props.selectedTrack) return
  
  const keyframes = [...props.selectedTrack.keyframes].sort((a, b) => a.time - b.time)
  const nextKeyframe = keyframes.find(k => k.time > props.currentTime)
  
  if (nextKeyframe) {
    seekToTime(nextKeyframe.time)
  } else if (keyframes.length > 0) {
    // 如果没有下一个，跳到第一个
    seekToTime(keyframes[0].time)
  }
}

// 开始拖动时间指示器
const startTimeIndicatorDrag = (event: MouseEvent) => {
  dragState.value = {
    isDragging: true,
    type: 'indicator',
    startX: event.clientX,
    startY: event.clientY,
    targetId: '',
    originalValue: props.currentTime
  }
  
  document.addEventListener('mousemove', handleDragThrottled)
  document.addEventListener('mouseup', endDrag)
}

// 开始拖动关键帧
const startKeyframeDrag = (keyframe: Keyframe, event: MouseEvent) => {
  dragState.value = {
    isDragging: true,
    type: 'keyframe',
    startX: event.clientX,
    startY: event.clientY,
    targetId: keyframe.id,
    originalValue: keyframe.time
  }
  
  document.addEventListener('mousemove', handleDragThrottled)
  document.addEventListener('mouseup', endDrag)
}

// 处理拖动
const handleDrag = (event: MouseEvent) => {
  if (!dragState.value.isDragging) return
  
  const deltaX = event.clientX - dragState.value.startX
  const deltaTime = deltaX / zoom.value
  
  if (dragState.value.type === 'indicator') {
    // 拖动时间指示器
    const newTime = Math.max(0, Math.min(props.totalDuration, 
      (dragState.value.originalValue as number) + deltaTime))
    emit('update:current-time', newTime)
  } else if (dragState.value.type === 'keyframe') {
    // 拖动关键帧
    if (!props.selectedTrack) return
    
    const keyframe = props.selectedTrack.keyframes.find(k => k.id === dragState.value.targetId)
    if (!keyframe) return
    
    const newTime = Math.max(0, Math.min(props.totalDuration, 
      (dragState.value.originalValue as number) + deltaTime))
    
    emit('update-keyframe', props.selectedTrack, {
      ...keyframe,
      time: newTime
    })
  }
}

// 使用节流优化拖动处理
const handleDragThrottled = throttle(handleDrag, 16)

// 结束拖动
const endDrag = () => {
  dragState.value.isDragging = false
  document.removeEventListener('mousemove', handleDragThrottled)
  document.removeEventListener('mouseup', endDrag)
}

// 生命周期钩子
onMounted(() => {
  // 可以添加额外的初始化逻辑
})

onBeforeUnmount(() => {
  // 清理事件监听器
  document.removeEventListener('mousemove', handleDragThrottled)
  document.removeEventListener('mouseup', endDrag)
})
</script>

<style lang="scss" scoped>
.timeline-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid var(--border-color-base);
  border-radius: 4px;
  
  .timeline-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px;
    border-bottom: 1px solid var(--border-color-base);
    background-color: var(--card-color);
    
    .header-actions {
      display: flex;
    }
    
    .header-center {
      flex: 1;
      display: flex;
      justify-content: center;
    }
  }
  
  .timeline-body {
    display: flex;
    flex: 1;
    overflow: hidden;
    
    .timeline-sidebar {
      width: 160px;
      border-right: 1px solid var(--border-color-base);
      display: flex;
      flex-direction: column;
      background-color: var(--card-color);
      
      .track-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 8px;
        height: 24px;
        background-color: var(--card-color);
        border-bottom: 1px solid var(--border-color-base);
        
        span {
          font-size: 12px;
          font-weight: 500;
        }
      }
      
      .track-list {
        flex: 1;
        overflow-y: auto;
      }
    }
    
    .timeline-content {
      flex: 1;
      position: relative;
      overflow: auto;
      
      .timeline-tracks-container {
        position: relative;
        
        .track-content {
          height: 30px;
          border-bottom: 1px solid var(--border-color-base);
          position: relative;
          
          &.selected {
            background-color: var(--primary-color-hover);
          }
        }
      }
    }
  }
}
</style> 